package com.chen106106.sstest.action;



import com.chen106106.sstest.common.JSONUtils;
import com.chen106106.sstest.common.PageHolder;
import com.chen106106.sstest.model.User;
import com.chen106106.sstest.service.UserMgrService;
import com.opensymphony.xwork2.ActionSupport;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 处理与用户相关的请求
 * @author chenz106106@gmail.com
 * 2012-7-16 下午11:33:55
 *
 */
public class UserMgrAction extends ActionSupport{

	private UserMgrService userMgrService;
	
	private Logger log = Logger.getLogger(UserMgrAction.class);
	
	HttpServletRequest request = ServletActionContext.getRequest();
	HttpServletResponse response = ServletActionContext.getResponse();
	
	private String username;
	
	private String password;
	
	private int uid;
	
	private PageHolder<User> pageHolder = new PageHolder<User>(10);
	
	public void setUsername(String username) {
		this.username = username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setUid(int uid) {
		this.uid = uid;
	}
	
	
	public PageHolder getPageHolder() {
		return pageHolder;
	}

	public void setPageHolder(PageHolder pageHolder) {
		this.pageHolder = pageHolder;
	}

	@Autowired
	public void setUserMgrService(UserMgrService userMgrService){
		this.userMgrService = userMgrService;
	}
	
	@Action(value="register",results={@Result(name = SUCCESS, type = "dispatcher", location = "/user/index.jsp"),
			@Result(name = INPUT, type = "dispatcher", location = "/index.jsp") })
	public String register(){
		
		
		User user = new User();
		try {
		if(!StringUtils.isEmpty(username)){
			username = URLDecoder.decode(username, "utf-8");
		}
		if(!StringUtils.isEmpty(password)){
			password = URLDecoder.decode(password, "utf-8");
		}
		}catch(Exception e){
			log.error(e.getMessage(),e);
		}
		user.setUsername(username);
		user.setPassword(password);
		long result = userMgrService.userRegister(user);
		
		Map<String,Object> jsonMap = new HashMap<String,Object>();
		jsonMap.put("result", result);
		String json = JSONObject.fromObject(jsonMap).toString();
		JSONUtils.ajaxWrite(response, json);
		return NONE;
	}
	//不写type的时候，默认就是dispatcher的方式，主要这里如果前台是通过ajax方式发送请求的，那么后台的type应该设置成dispatcher方式，否则数据返回不了。
	@Action(value="user-list",results={@Result(name=SUCCESS,type="dispatcher",location="/user/li.jsp")})
	public String userList(){
		
//		int beginIndex = 1;
//		int num = 30;
//		int[]params = new int[]{beginIndex,num};
		
		
//		pHolder.setPageIndex();//当前页的页码
//		pHolder.setPageSize();//每页的大小
//
//		pHolder.setRowCount(dao.count(...));//获取数据库里的总记录数
//		pHolder.setList(dao.list(...));//从数据库获取当前页的数据
		
		int rowCount = userMgrService.getUserCount();
		pageHolder.setRowCount(rowCount);
		
		int pageSize = pageHolder.getPageSize();
		int offSet = pageHolder.getRowOffset();
		int [] params = new int[]{offSet,pageSize};
		List<User>users = userMgrService.queryList(params);
		request.setAttribute("userList", users);
		pageHolder.setList(users);
		return SUCCESS;
		
	}
	@Action(value="update-user",results={@Result(name=SUCCESS,location="/user/update-user.jsp")})
	public String updateUser(){
		boolean result = false;
		try{
			if(0!=uid){
				User user = new User();
				user.setId(uid);
				user.setPassword(password);
				user.setUsername(username);
				result = userMgrService.updateUser(user);
			}
			
		}catch(Exception e){
			log.error(e.getMessage(),e);
		}
		Map<String,Object> jsonResult = new HashMap<String, Object>();
		jsonResult.put("result", result);
		String json = JSONObject.fromObject(jsonResult).toString();
		JSONUtils.ajaxWrite(response, json);
		return NONE;
	}
	
	
	@Action(value="get-user-info",results={@Result(name=SUCCESS,location="/user/update-user.jsp")})
	public String getUserInfo(){
		String userId = request.getParameter("user_id");
		User user = null;
		try{
			if(!StringUtils.isEmpty(userId)){
				user = userMgrService.getUserInfoById(Integer.parseInt(userId));
			}
			
		}catch(Exception e){
			log.error(e.getMessage(),e);
		}
		Map<String,Object> jsonResult = new HashMap<String, Object>();
		jsonResult.put("user", user);
		String json = JSONObject.fromObject(jsonResult).toString();
		JSONUtils.ajaxWrite(response, json);
		return NONE;
	}
	
	@Action(value="delete-user",results={@Result(name=SUCCESS,location="/user/update-user.jsp")})
	public String deleteUser(){
		boolean result = false;
		try{
			if(0!=uid){
			
				result = userMgrService.deleteUser(uid);
			}
			
		}catch(Exception e){
			log.error(e.getMessage(),e);
		}
		Map<String,Object> jsonResult = new HashMap<String, Object>();
		jsonResult.put("result", result);
		String json = JSONObject.fromObject(jsonResult).toString();
		JSONUtils.ajaxWrite(response, json);
		return NONE;
	}
}
